var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
  // If the importer is in node compatibility mode or this is not an ESM
  // file that has been converted to a CommonJS file using a Babel-
  // compatible transform (i.e. "__esModule" has not been set), then set
  // "default" to the CommonJS "module.exports" for node compatibility.
  isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
  mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);

// src/businessComponent/Attachment/AttachmentContext.tsx
var AttachmentContext_exports = {};
__export(AttachmentContext_exports, {
  AttachmentContext: () => AttachmentContext,
  AttachmentProvider: () => AttachmentProvider,
  DEFAULT_ATTACHMENT_UPLOAD_MAX_COUNT: () => DEFAULT_ATTACHMENT_UPLOAD_MAX_COUNT,
  useAttachment: () => useAttachment
});
module.exports = __toCommonJS(AttachmentContext_exports);
var import_react = __toESM(require("react"));
var import_functionalComponent = require("../../functionalComponent");
var import_util = require("../../util");
var import_api = require("./api");
var import_service = require("./service");
var import_util2 = require("./util");
var DEFAULT_ATTACHMENT_RECORD_LIST = [];
var DEFAULT_ATTACHMENT_UPLOAD_MAX_COUNT = 99;
var AttachmentContext = (0, import_react.createContext)({
  mergeChunks: async () => ({ fileId: "" }),
  upload: async () => {
  },
  beforeUploadValidate: async () => true,
  maxCount: DEFAULT_ATTACHMENT_UPLOAD_MAX_COUNT,
  disabled: false,
  uploadThreadCount: 3,
  chunkSize: 5242880,
  actions: {
    delete: async () => false,
    zipDownload: async () => {
    },
    isPreview: () => false,
    preview: async () => {
    },
    download: async () => {
    },
    openTableAttachment: async () => {
    }
  },
  onContentChanged: async () => {
  },
  attachmentRecordList: [],
  loading: false,
  permission: {
    add: 1,
    delete: 1,
    edit: 1,
    view: 1,
    preview: 1,
    download: 1,
    zipDownload: 1,
    manage: 1
  },
  isReady: false,
  uploading: false,
  attachmentFileList: [],
  onUploadStateChange: () => {
  },
  approved: 0
});
var useAttachmentRecordList = (attachmentRecordList = DEFAULT_ATTACHMENT_RECORD_LIST) => {
  const uploadedFilesRef = (0, import_react.useRef)({});
  const [upLoadingFileList, setUpLoadingFileList] = (0, import_react.useState)([]);
  const [uploading, setUploading] = (0, import_react.useState)(false);
  const onUploadStateChange = (0, import_util.useRefCallback)((state, _uploading) => {
    setUploading(_uploading);
    const { progress } = state;
    const list = Object.values(progress);
    setUpLoadingFileList(list);
    list.forEach((v) => {
      if (!uploadedFilesRef.current[v.fileName]) {
        uploadedFilesRef.current[v.fileName] = v.status === "done";
      }
    });
  });
  const attachmentFileList = (0, import_react.useMemo)(() => {
    const names = [];
    const uploadedFileList = attachmentRecordList.map((data) => {
      const uploaded = uploadedFilesRef.current[data.asrName];
      names.push(data.asrName);
      return {
        ...data,
        fileName: data.asrName,
        status: uploaded ? "done" : void 0
      };
    });
    const list = upLoadingFileList.filter((file) => !names.includes(file.fileName) && file.status !== "error");
    return [...list, ...uploadedFileList];
  }, [upLoadingFileList, attachmentRecordList]);
  const removeFiles = (0, import_util.useRefCallback)((fileNames) => {
    if (fileNames.length === 0) {
      return;
    }
    fileNames.forEach((name) => uploadedFilesRef.current[name] = false);
    setUpLoadingFileList((list) => list.filter((v) => !fileNames.includes(v.fileName)));
  });
  const reset = (0, import_util.useRefCallback)(() => {
    uploadedFilesRef.current = {};
    setUpLoadingFileList([]);
    setUploading(false);
  });
  return {
    uploading,
    removeFiles,
    attachmentFileList,
    onUploadStateChange,
    reset
  };
};
var AttachmentProvider = (0, import_react.forwardRef)(({ children, ...rest }, ref) => {
  var _a, _b, _c;
  const {
    disabled: propDisabled,
    busTypeCode: propBusTypeCode,
    uCode: propUCode,
    asrTable: propAsrTable,
    asrCode: propAsrCode,
    asrSessionGuid: propAsrSessionGuid,
    value,
    // eslint-disable-next-line react-hooks/rules-of-hooks
    apiRef = (0, import_react.useRef)({}),
    onChange,
    permission: propsPermission,
    asrFill: propAsrFill,
    asrFillName: propAsrFillName,
    unitNo,
    orgNo,
    projectNo,
    asrAttachTable = "",
    busUrl,
    approved = 0,
    maxCount = DEFAULT_ATTACHMENT_UPLOAD_MAX_COUNT,
    uploadThreadCount = 3,
    chunkSize = 5242880,
    customOpenTab,
    onSave,
    fileTypeCode = "",
    accept,
    bizCode = (_a = import_util.iup.getPageInstance()) == null ? void 0 : _a.busType
  } = rest;
  const disabled = propDisabled;
  const busTypeCode = propBusTypeCode || ((_b = import_util.iup.getPageInstance()) == null ? void 0 : _b.busType);
  const asrSessionGuid = propAsrSessionGuid || value || "";
  const asrTable = propAsrTable || value;
  const asrCode = propAsrCode || value;
  const innerRef = (0, import_react.useRef)({ isChanged: false, cancelId: import_util.iup.uniqueId("get_attachment_list") });
  const [attachmentRecordList, setAttachmentRecordList] = (0, import_react.useState)();
  const uploadingRef = (0, import_react.useRef)(false);
  const [loading, setLoading] = (0, import_react.useState)(false);
  const onChangeCallback = (0, import_util.useRefCallback)(() => {
    if (asrSessionGuid !== apiRef.current.asrSessionGuid && apiRef.current.asrSessionGuid && onChange) {
      onChange(apiRef.current.asrSessionGuid);
    }
  });
  const getTableAttach = (0, import_util.useRefCallback)(async (updateFlg = false) => {
    innerRef.current.loadPromise = new Promise(async (resolve, reject) => {
      try {
        setLoading(true);
        if (apiRef.current.asrSessionGuid) {
          apiRef.current = {
            ...apiRef.current,
            attachmentRecordList: await (0, import_service.getTempAttachment)({ cursorId: apiRef.current.asrSessionGuid })
          };
          if (updateFlg) {
            onChangeCallback();
          }
        } else {
          apiRef.current.asrSessionGuid = asrSessionGuid;
          const result = await (0, import_api.getTableAttachmentApi)(
            {
              asrSessionGuid,
              asrFill: propAsrFill,
              asrFillName: propAsrFillName,
              unitNo,
              orgNo,
              projectNo,
              uCode: propUCode,
              approved,
              asrTable,
              asrCode,
              asrAttachTable,
              busTypeCode,
              busUrl,
              customOpenTab,
              onSave,
              fileTypeCode,
              bizCode
            },
            innerRef.current.cancelId
          );
          apiRef.current = result;
        }
        setLoading(false);
        setAttachmentRecordList(apiRef.current.attachmentRecordList);
        resolve(apiRef.current);
        innerRef.current.loadPromise = void 0;
      } catch (error) {
        if (error.message !== "CancelTokenError") {
          setLoading(false);
          reject(error);
          innerRef.current.loadPromise = void 0;
        }
      }
    });
    await innerRef.current.loadPromise;
  });
  const { uploading, onUploadStateChange, attachmentFileList, removeFiles, reset } = useAttachmentRecordList(attachmentRecordList);
  uploadingRef.current = uploading;
  (0, import_react.useEffect)(() => {
    if (apiRef.current.asrSessionGuid === asrSessionGuid) {
      return;
    }
    apiRef.current.asrSessionGuid = "";
    reset();
    getTableAttach();
  }, [asrSessionGuid, reset]);
  (0, import_react.useImperativeHandle)(
    ref,
    () => ({
      getApi: () => {
        return {
          ...apiRef.current,
          async getCount() {
            var _a2, _b2, _c2;
            if (innerRef.current.loadPromise) {
              const result = await innerRef.current.loadPromise;
              return ((_a2 = result == null ? void 0 : result.attachmentRecordList) == null ? void 0 : _a2.length) || 0;
            }
            return ((_c2 = (_b2 = apiRef.current) == null ? void 0 : _b2.attachmentRecordList) == null ? void 0 : _c2.length) || 0;
          },
          getResult() {
            return innerRef.current.loadPromise || apiRef.current;
          },
          isChanged() {
            return innerRef.current.isChanged;
          },
          uploadingRef
        };
      }
    }),
    []
  );
  const upload = (0, import_util.useRefCallback)((data) => {
    return (0, import_service.uploadFile)({
      ...data,
      busiType: fileTypeCode,
      cursorId: apiRef.current.asrSessionGuid || "",
      bizCode,
      unitNo,
      // todo 以下选填
      ctlgId: ""
    }).then((res) => {
      if (res.code !== 0) {
        const err = new Error(res.message);
        err.name = "api";
        throw err;
      }
      return res;
    });
  });
  const mergeChunks = (0, import_util.useRefCallback)((md5, totalChunks) => {
    return (0, import_service.mergeChunks)({
      md5,
      totalChunks,
      busiType: fileTypeCode,
      cursorId: apiRef.current.asrSessionGuid || ""
    });
  });
  const existedFileNames = (0, import_react.useMemo)(
    () => attachmentFileList.filter((v) => {
      return v.status !== "fail" && v.status !== "error";
    }).map((item) => item.fileName),
    [attachmentFileList]
  );
  const beforeUploadValidate = (0, import_util.useRefCallback)(async (file, fileList) => {
    var _a2;
    const suffix = (0, import_util2.getFileType)(file.name);
    const fileText = `文件（${file.name}）的`;
    const { tableAttachInfo: attachInfo } = apiRef.current;
    if (file.size === 0) {
      import_functionalComponent.message.error(`文件 ${file.name} 无任何内容，无法上传`);
      return false;
    }
    if (attachInfo == null ? void 0 : attachInfo.specialChars) {
      for (const str of attachInfo == null ? void 0 : attachInfo.specialChars) {
        if (file.name.includes(str)) {
          import_functionalComponent.message.error(fileText + "文件名包含特殊符号，无法上传");
          return false;
        }
      }
    }
    const fileWhiteList = attachInfo == null ? void 0 : attachInfo.fileWhiteList;
    if (accept || fileWhiteList) {
      const fileWhiteListArr = (accept ?? fileWhiteList).split(",").map((item) => item[0] === "." ? item : `.${item}`);
      if (!fileWhiteListArr.includes(`.${suffix}`)) {
        import_functionalComponent.message.error(`不允许文件格式为${suffix}的附件上传，请重新上传`);
        return false;
      }
    }
    if (existedFileNames.includes(file.name)) {
      import_functionalComponent.message.error(fileText + "文件名已存在");
      return false;
    }
    if (fileList.length + ((_a2 = apiRef.current.attachmentRecordList) == null ? void 0 : _a2.length) > maxCount) {
      import_functionalComponent.message.error(`文件数量已达到上限${maxCount}个，无法上传新文件`);
      return false;
    }
    return true;
  });
  const permission = (0, import_react.useMemo)(() => {
    return {
      add: disabled ? 0 : 1,
      delete: disabled ? 0 : 1,
      edit: disabled ? 0 : 1,
      view: 1,
      preview: 1,
      download: 1,
      zipDownload: 1,
      ...propsPermission
    };
  }, [disabled, propsPermission]);
  const openTableAttachment = (0, import_util.useRefCallback)((configs) => {
    return (0, import_api.openFormTableAttachment)(
      {
        ...apiRef.current,
        async getCount() {
          var _a2, _b2, _c2;
          if (innerRef.current.loadPromise) {
            const result = await innerRef.current.loadPromise;
            return ((_a2 = result == null ? void 0 : result.attachmentRecordList) == null ? void 0 : _a2.length) || 0;
          }
          return ((_c2 = (_b2 = apiRef.current) == null ? void 0 : _b2.attachmentRecordList) == null ? void 0 : _c2.length) || 0;
        },
        getResult() {
          return innerRef.current.loadPromise || apiRef.current;
        },
        uploadingRef
      },
      configs
    );
  });
  const onContentChanged = (0, import_util.useRefCallback)(() => {
    innerRef.current.isChanged = true;
    getTableAttach(true);
  });
  const actions = (0, import_react.useMemo)(() => {
    return {
      delete: async (list) => {
        var _a2, _b2;
        const ids = [];
        const tmpFileNames = list.map((v) => {
          if (v.asrFid) {
            ids.push(v.asrFid);
          }
          return v.fileName;
        });
        if (ids.length > 0) {
          const res = await ((_b2 = (_a2 = apiRef.current) == null ? void 0 : _a2.handleDelete) == null ? void 0 : _b2.call(_a2, ids.join(",")));
          if (res) {
            removeFiles(tmpFileNames);
            onContentChanged();
          }
          return res;
        } else {
          removeFiles(tmpFileNames);
          return true;
        }
      },
      zipDownload: () => {
        var _a2, _b2;
        return (_b2 = (_a2 = apiRef.current).handleZipDownload) == null ? void 0 : _b2.call(_a2);
      },
      isPreview: (fileName) => {
        var _a2;
        const previewFileType = (_a2 = apiRef.current.tableAttachInfo) == null ? void 0 : _a2.previewFileType;
        if (!previewFileType) {
          return false;
        }
        return previewFileType.includes((0, import_util2.getFileType)(fileName));
      },
      preview: (fileId) => {
        var _a2, _b2;
        return (_b2 = (_a2 = apiRef.current).handlePreview) == null ? void 0 : _b2.call(_a2, { asrFid: fileId });
      },
      download: (data) => {
        var _a2, _b2;
        return (_b2 = (_a2 = apiRef.current).handleDownload) == null ? void 0 : _b2.call(_a2, data);
      },
      openTableAttachment
    };
  }, []);
  return /* @__PURE__ */ import_react.default.createElement(
    AttachmentContext.Provider,
    {
      value: {
        mergeChunks,
        upload,
        beforeUploadValidate,
        maxCount,
        disabled,
        uploadThreadCount,
        chunkSize,
        actions,
        attachmentRecordList: attachmentRecordList || [],
        loading,
        permission,
        isReady: !!apiRef.current.asrSessionGuid,
        uploading,
        onUploadStateChange,
        attachmentFileList,
        approved,
        accept: accept || ((_c = apiRef.current.tableAttachInfo) == null ? void 0 : _c.fileWhiteList),
        onContentChanged
      }
    },
    children
  );
});
var useAttachment = () => {
  const context = (0, import_react.useContext)(AttachmentContext);
  if (!context) {
    throw new Error("useAttachment must be used within a AttachmentProvider");
  }
  return context;
};
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  AttachmentContext,
  AttachmentProvider,
  DEFAULT_ATTACHMENT_UPLOAD_MAX_COUNT,
  useAttachment
});
